package com.wuzheng.wisgo.sanitation.cloud.service.person.impl;

import com.auth0.jwt.JWT;
import com.wuzheng.wisgo.sanitation.cloud.model.person.param.LoginParam;
import com.wuzheng.wisgo.sanitation.cloud.model.person.pojo.LoginReturnDto;
import com.wuzheng.wisgo.sanitation.cloud.repository.entity.person.User;
import com.wuzheng.wisgo.sanitation.cloud.repository.mapper.person.UserMapper;
import com.wuzheng.wisgo.sanitation.cloud.service.person.TokenService;
import com.wuzheng.wisgo.sanitation.cloud.constant.ErrorConst;
import com.wuzheng.wisgo.sanitation.framework.util.Assert;
import com.wuzheng.wisgo.sanitation.framework.util.BeanUtils;
import com.wuzheng.wisgo.sanitation.cloud.service.person.UserService;
import com.wuzheng.wisgo.sanitation.framework.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author：hibon
 * @date：Created in 2019-09-22
 * @description：用户信息 服务实现类
 * @modified By：
 * @version: 1.0
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Resource
    TokenService tokenService;
    @Value("${token.auth.redis.expire}")
    private Integer redisExpire;
    @Resource(name = "redisTemplate")
    private RedisTemplate redis;

    @Override
    public LoginReturnDto selectUser(LoginParam loginParam) {
        User user = this.getMapper(UserMapper.class).selectUserByLogin(loginParam);
        Assert.isTrue(user != null, ErrorConst.User.NAME_OR_PWD_ERROR);
        LoginReturnDto loginReturnDto = new LoginReturnDto();
        BeanUtils.copyPropertiesAllowNull(user, loginReturnDto);

        String token = tokenService.getToken(user);
        loginReturnDto.setToken(token);

        redis.boundValueOps(token).set(loginReturnDto, redisExpire, TimeUnit.SECONDS);
        return loginReturnDto;
    }

    @Override
    public User getToken(String token) {
        String userId = JWT.decode(token).getAudience().get(0);
        Object object = redis.opsForValue().get(token);
        User user = new User();
        if (object != null) {
            LoginReturnDto loginReturnDto = (LoginReturnDto) object;
            BeanUtils.copyPropertiesAllowNull(loginReturnDto, user);
            return user;
        }
        user = this.selectById(userId);
        LoginReturnDto loginReturnDto = new LoginReturnDto();
        BeanUtils.copyPropertiesAllowNull(user, loginReturnDto);
        redis.boundValueOps(token).set(loginReturnDto, redisExpire, TimeUnit.SECONDS);
        return user;
    }
}
